import GROUP_DATA from '../../utils/groups.js'

Page({
  data: {
    questions: [],
    currentQuestion: 0,
    selectedOption: null,
    showResult: false,
    score: 0
  },

  onLoad(options) {
    const groupId = options.groupId;
    const groupData = GROUP_DATA.find(item => item.group.group_id === groupId);
    
    if (groupData) {
      // 生成测试题目
      const questions = this.generateQuestions(groupData.words);
      this.setData({ questions });
    }
  },

  generateQuestions(words) {
    // 复制并打乱单词数组
    const shuffledWords = [...words].sort(() => Math.random() - 0.5);
    
    return shuffledWords.map(word => {
      // 为每个问题生成选项
      const options = this.generateOptions(word, words);
      return {
        word: word.word_english,
        word_chinese: word.word_chinese,
        correctImage: word.word_image,
        options: options
      };
    });
  },

  generateOptions(correctWord, allWords) {
    // 获取3个错误选项
    const wrongOptions = allWords
      .filter(w => w.word_english !== correctWord.word_english)
      .sort(() => Math.random() - 0.5)
      .slice(0, 3)
      .map(w => ({
        image: w.word_image,
        word_chinese: w.word_chinese,
        isCorrect: false
      }));

    // 添加正确选项
    const options = [
      {
        image: correctWord.word_image,
        word_chinese: correctWord.word_chinese,
        isCorrect: true
      },
      ...wrongOptions
    ];

    // 打乱选项顺序
    return options.sort(() => Math.random() - 0.5);
  },

  selectOption(e) {
    if (this.data.showResult) return;
    
    const index = e.currentTarget.dataset.index;
    const questions = this.data.questions;
    
    questions[this.data.currentQuestion].options.forEach((option, i) => {
      option.selected = i === index;
    });

    this.setData({
      questions,
      selectedOption: index,
      showResult: true,
      score: this.data.score + (questions[this.data.currentQuestion].options[index].isCorrect ? 1 : 0)
    });
  },

  nextQuestion() {
    if (this.data.selectedOption === null) return;

    if (this.data.currentQuestion === this.data.questions.length - 1) {
      wx.navigateTo({
        url: `/pages/testResult/testResult?score=${this.data.score}&total=${this.data.questions.length}`
      });
      return;
    }

    this.setData({
      currentQuestion: this.data.currentQuestion + 1,
      selectedOption: null,
      showResult: false
    });
  }
}); 